package com.ljb.baseadapter_listview;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

/**
 * 多种行视图的Adapter
 * Created by lijianbin on 2016/12/13.
 */
public class MutiItemTypeAdapter<T> extends BaseAdapter {
    private ItemViewTemplateController controller;
    protected Context mContext;
    protected List<T> mDatas;

    public MutiItemTypeAdapter(Context context, List<T> datas) {
        controller = new ItemViewTemplateController();
        mContext = context;
        mDatas = datas;
    }

    /**
     * 添加模板到模板集合
     */
    public MutiItemTypeAdapter addItemViewTemplate(ItemViewTemplate itemViewTemplate) {
        controller.addTemplate(itemViewTemplate);
        return this;
    }

    /**
     * 判断是否是多种行视图
     */
    private boolean isMutiItemType() {
        return controller.getItemViewTemplatesCount() > 0;
    }

    @Override
    public int getViewTypeCount() {
        if (isMutiItemType()) {
            return controller.getItemViewTemplatesCount();
        }
        return super.getViewTypeCount();
    }

    @Override
    public int getItemViewType(int position) {
        if (isMutiItemType()) {
            return controller.getItemViewType(getItem(position), position);
        }
        return super.getItemViewType(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ItemViewTemplate template = controller.getItemViewTemplate(getItem(position), position);
        int layoutId = template.getItemViewLayoutId();
        ViewHolder holder = ViewHolder.getHolder(mContext, convertView, parent, layoutId, position);
        convert(holder, getItem(position), position);
        return holder.getConvertView();
    }

    /**
     * 数据转化
     */
    protected void convert(ViewHolder holder, T item, int position) {
        controller.convert(holder, item, position);
    }

    @Override
    public int getCount() {
        return mDatas.size();
    }

    @Override
    public T getItem(int position) {
        return mDatas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
}
